import React, { useEffect, useState } from 'react';
import {
  Modal,
  View,
  Image,
  Text,
  TouchableWithoutFeedback,
  PanResponder,
  FlatList,
} from 'react-native';
import { FlatListSm, FlatListTm, TitleBar } from './index';
import i18n from '../i18n';
import stylesXS from '../styles/xs';
import stylesMD from '../styles/md';
import stylesLG from '../styles/lg';

import dimesA5 from '../styles/size/a5';
import dimesA5X2 from '../styles/size/a5x2';
import dimesA6 from '../styles/size/nom';
import {
  GestureHandlerRootView,
  PanGestureHandler,
  State
} from 'react-native-gesture-handler';
import { checkArray } from '../utils/jsUtils';

const ModalSelectSticker = ({
  modalVisible,
  data,
  onConfirm,
  checkId,
  onClose,
  screenHeight,
  screenWidth,
}) => {
  const [currentPage, setCurrentPage] = useState(1);
  const [pages, setPages] = useState([1, 2, 3, 4, 5, 6, 7, 8, 9, 0]);
  const [showPageStatus, setShowPageStatus] = useState(false);
  // 跳转的页码
  const [jumpNum, setJumpNum] = useState("");

  let wd = Math.round(screenWidth);
  const itemsPerPage = screenWidth < screenHeight ? 20 : 24; // 每页显示的项目数
  const paginatedItems = data?.slice(
    (currentPage - 1) * itemsPerPage,
    currentPage * itemsPerPage,
  );
  const pagesList = checkArray(data, itemsPerPage);
  const totalPages = Math.ceil(data?.length / itemsPerPage);
  const handleFirstPage = () => setCurrentPage(1);

  // 设置跳转的页码
  const handJumpNum = (num) => {
    var newNum = 0;
    if (jumpNum.trim()) {
      newNum = parseInt(jumpNum);
    }
    console.log("handJumpNum newNum:" + newNum);

    newNum = newNum * 10 + num;
    console.log("handJumpNum newNum1:" + newNum + "==" + num + "==" + totalPages);
    if (newNum > totalPages) {
      return;
    }
    if (newNum === 0) {
      setJumpNum("0");
    } else {
      setJumpNum(jumpNum + num);
    }

  }
  // 删除跳转页码最后一位
  const deleteJumpNum = () => {
    if (!jumpNum.trim()) {
      return;
    }
    setJumpNum(jumpNum.slice(0, -1));


  }

  const handleGoPage = () => {
    if (!jumpNum.trim()) {
      return;
    }
    var num = parseInt(jumpNum);
    console.log("handleGoPage num:" + num);
    if (num > 0) {
      setCurrentPage(num);
    }

    setJumpNum("");
  };

  const handlePreviousPage = () =>
    setCurrentPage(prevPage => Math.max(prevPage - 1, 1));
  const handleNextPage = () =>
    setCurrentPage(prevPage => Math.min(prevPage + 1, totalPages));
  const handleLastPage = () => setCurrentPage(totalPages);
  const styles =
    wd === 1024 || wd === 1365
      ? stylesLG
      : wd === 994 || wd === 1325
        ? stylesMD
        : stylesXS;
  const nom = wd === 1024 || wd === 1365
    ? dimesA5X2
    : wd === 994 || wd === 1325
      ? dimesA5
      : dimesA6;
  console.log("ModalSelectSticker wd:" + wd);
  const itemMarginRight = screenWidth < screenHeight ?
    Math.floor((screenWidth - nom.dp_px_80 * 2 - 4 * styles.modalIteSty.width) / 3)
    : Math.floor((screenWidth - nom.dp_px_80 * 2 - 6 * styles.modalIteSty.width) / 5);

  console.log("ModalSelectSticker itemMarginRight:" + itemMarginRight);
  const itemMarginBottom = screenWidth < screenHeight ?
    (screenHeight - styles.titleHeight.height * 2
      - nom.dp_px_48 * 2 - 5 * styles.modalIteSty.width
      - 5 * nom.dp_px_48) / 4
    : (screenHeight - styles.titleHeight.height * 2
      - nom.dp_px_48 * 2 - 4 * styles.modalIteSty.width
      - 4 * nom.dp_px_48) / 3

  const [firstTopWidth, setFirstTopWidth] = useState(nom.dp_px_2);
  const [endTopWidth, setEndTopWidth] = useState(nom.dp_px_2);
  const [isPressButton, setIsPressButton] = useState(false);
  return (
    <Modal animationType="none" transparent={true} visible={modalVisible}>
      <View style={styles.container}>

        <View
          style={[
            styles.container,
            { width: screenWidth, height: screenHeight },
          ]}>
          <TitleBar
            backgroundColor={'#fff'}
            textColor={'#000'}
            textRightColor={'#999'}
            onBack={() => {
              onClose();
              setCurrentPage(1);
            }}
            title={i18n.t('title.coll')}
            status={'select'}
            rightBtnStatus={false}
            screenWidth={screenWidth}
            screenHeight={screenHeight}
            sWidth={{ width: screenWidth }}
          />
          <GestureHandlerRootView>
            <PanGestureHandler
              onHandlerStateChange={event => {
                const nativeEvent = event.nativeEvent;
                console.log(
                  'PanGestureHandler onHandlerStateChange velocityX:' +
                  nativeEvent.velocityX +
                  '==' +
                  nativeEvent.translationX + "==" + nativeEvent.state
                );
                if (nativeEvent.state === State.END || nativeEvent.state === State.CANCELLED) {
                  /// 判断是否是滑动事件，x轴滑动速度要大于300，滑动距离大于100
                  /// x轴滑动距离要大于y轴距离的3分之一，满足以上条件才是滑动事件
                  if (
                    Math.abs(nativeEvent.velocityX) > 1000 &&
                    Math.abs(nativeEvent.translationX) >= 100 &&
                    Math.abs(nativeEvent.translationX) >=
                    Math.abs(nativeEvent.translationY) * 3
                  ) {
                    /// 小于0前翻
                    if (nativeEvent.translationX < 0) {
                      handleNextPage();
                    } else {
                      handlePreviousPage();
                    }
                  }
                }
              }}>
              <View
                style={[
                  // styles.paddingHor_60,
                  {
                    height: screenHeight - styles.titleHeight.height * 2,
                    width: screenWidth,
                    flexWrap: 'wrap',
                    paddingVertical: nom.dp_px_48,
                    paddingHorizontal: nom.dp_px_80,

                  },
                ]}>
                <FlatListTm
                  list={paginatedItems}
                  onItemPress={item => {
                    console.log("ModalSelectSticker onItemPress item:", item);
                    onConfirm(item);
                    setCurrentPage(1);
                  }}
                  checkId={checkId}
                  screenWidth={screenWidth}
                  screenHeight={screenHeight}
                  bodyStyle={[
                    {
                      width: screenWidth - nom.dp_px_80 * 2,
                      height: screenHeight - styles.titleHeight.height * 2 - nom.dp_px_48 * 2,
                    },
                  ]}
                  itemStyle={[
                    styles.modalIteSty,
                    {

                      marginRight: itemMarginRight,
                      marginBottom: itemMarginBottom

                    },
                    styles.modalCardBody,
                  ]}
                  status={'create'}
                />
              </View>
            </PanGestureHandler>
          </GestureHandlerRootView>
          <View
            style={[
              {
                width: screenWidth,
                position: 'absolute',
                bottom: 0,
                left: 0,
                backgroundColor: '#fff',
              },
              styles.titleHeight,
              styles.borderTopWidth,
              styles.flexCenter,
            ]}>
            <View
              style={{
                flexDirection: 'row',
                alignItems: 'center',
              }}>
              <TouchableWithoutFeedback onPress={handleFirstPage}>
                <View style={{
                  width: nom.dp_px_92,
                  height: nom.dp_px_92,
                }}>
                  <Image
                    style={[styles.imgWdHt,
                    {
                      opacity: totalPages > 1 && currentPage > 1 ? 0 : 1,
                      position: 'absolute',
                      left: nom.dp_px_30,
                      top: nom.dp_px_30,

                    }]}
                    source={require('../../assets/ic_first_page_unable.png')}
                  />
                  <Image
                    style={[styles.imgWdHt,
                    {
                      opacity: totalPages > 1 && currentPage > 1 ? 1 : 0,
                      position: 'absolute',
                      left: nom.dp_px_30,
                      top: nom.dp_px_30,
                    }]
                    }
                    source={require('../../assets/ic_first_page.png')}
                  />


                </View>
              </TouchableWithoutFeedback>
              <TouchableWithoutFeedback onPress={handlePreviousPage}>
                <View style={{
                  width: nom.dp_px_92,
                  height: nom.dp_px_92,
                }}>

                  <Image
                    style={[styles.imgWdHt,
                    {
                      opacity: totalPages > 1 && currentPage > 1 ? 0 : 1,
                      position: 'absolute',
                      left: nom.dp_px_30,
                      top: nom.dp_px_30,

                    }]}
                    source={require('../../assets/ic_arrow_left_unable.png')}
                  />

                  <Image
                    style={[styles.imgWdHt,
                    {
                      opacity: totalPages > 1 && currentPage > 1 ? 1 : 0,
                      position: 'absolute',
                      left: nom.dp_px_30,
                      top: nom.dp_px_30,
                    }]
                    }
                    source={require('../../assets/ic_arrow_left.png')}
                  />

                </View>
              </TouchableWithoutFeedback>
            </View>
            <TouchableWithoutFeedback
              onPress={() => setShowPageStatus(true)}>
              <View style={
                [styles.titleHeight,
                {
                  alignItems: 'center',
                  justifyContent: 'center',
                  marginHorizontal:nom.dp_px_68
                }
                ]
              }>
                <View style={[styles.bottomBorder,
                {
                  flexDirection: 'row',
                  alignItems: 'center',
                  paddingVertical: nom.dp_px_5

                }
                ]}>
                  <Text
                    style={[
                      styles.fontSize_26,
                      {
                        fontWeight: '700',
                      },
                    ]}>{`${currentPage} / `}
                  </Text>
                  <Text
                    style={[
                      styles.fontSize_26,
                      {
                        fontWeight: '400',
                      },
                    ]}>{totalPages}
                  </Text>
                </View>
                
              </View>
            </TouchableWithoutFeedback>
            <View
              style={{
                flexDirection: 'row',
                alignItems: 'center',
              }}>
              <TouchableWithoutFeedback onPress={handleNextPage}>
                <View style={{
                  width: nom.dp_px_92,
                  height: nom.dp_px_92,
                }}>
                  <Image
                    style={[styles.imgWdHt,
                    {
                      opacity: totalPages > 1 && currentPage < totalPages ? 0 : 1,
                      position: 'absolute',
                      left: nom.dp_px_30,
                      top: nom.dp_px_30,

                    }]}
                    source={require('../../assets/ic_arrow_right_unable.png')}
                  />

                  <Image
                    style={[styles.imgWdHt,
                    {
                      opacity: totalPages > 1 && currentPage < totalPages ? 1 : 0,
                      position: 'absolute',
                      left: nom.dp_px_30,
                      top: nom.dp_px_30,
                    }]
                    }
                    source={require('../../assets/ic_arrow_right.png')}
                  />

                </View>
              </TouchableWithoutFeedback>
              <TouchableWithoutFeedback onPress={handleLastPage}>
                <View style={{
                  width: nom.dp_px_92,
                  height: nom.dp_px_92,
                }}>

                  <Image
                    style={[styles.imgWdHt,
                    {
                      opacity: totalPages > 1 && currentPage < totalPages ? 0 : 1,
                      position: 'absolute',
                      left: nom.dp_px_30,
                      top: nom.dp_px_30,

                    }]}
                    source={require('../../assets/ic_last_page_unable.png')}
                  />
                  <Image
                    style={[styles.imgWdHt,
                    {
                      opacity: totalPages > 1 && currentPage < totalPages ? 1 : 0,
                      position: 'absolute',
                      left: nom.dp_px_30,
                      top: nom.dp_px_30,
                    }]
                    }
                    source={require('../../assets/ic_last_page.png')}
                  />
                </View>
              </TouchableWithoutFeedback>
            </View>
          </View>
        </View>
        {showPageStatus ? (
          <TouchableWithoutFeedback
            onPress={() => {
              setJumpNum("");
              setShowPageStatus(false);
            }}
          >
            <View
              style={[

                {
                  width: screenWidth, height: screenHeight,
                  position: "absolute",
                  marginTop: 0,
                  marginBottom: 0
                },
              ]}>

              <TouchableWithoutFeedback onPress={() => { }}>
                <View
                  style={[
                    {
                      width: screenWidth,
                      position: 'absolute',
                      bottom: 0,
                      left: 0,
                      backgroundColor: '#fff',
                    },
                  ]}>

                  <View
                    style={[
                      { width: screenWidth },
                      styles.titleHeight,
                      styles.borderTopWidth,
                      styles.flexCenter,
                    ]}>

                    <View style={[styles.marginHor_118, styles.flexCenter]}>
                      <Text
                        style={[
                          styles.fontSize_34,
                          {
                            fontWeight: '400',
                          },
                        ]}>
                          [ <Text style={{fontWeight:'700'}}>{`${currentPage} `}</Text>
                          / {totalPages} ]</Text>
                      <Text
                        style={[
                          styles.fontSize_34,
                          { marginLeft: styles.fontSize_30.fontSize },
                        ]}>
                        {i18n.t('msg.jumpTo')}
                      </Text>
                      <View
                        style={[
                          styles.bottomBorder,
                          styles.justAlign,
                          styles.paddingVertical_15,
                          {
                            width: styles.marginBottom_150.marginBottom,
                            marginLeft: styles.searchInput.paddingLeft,
                            marginRight: styles.fontSize_26.fontSize,
                          },
                        ]}>

                        <Text style={[styles.fontSize_34]}>{jumpNum}</Text>

                      </View>
                      <TouchableWithoutFeedback

                        onPress={() => {
                          handleGoPage();
                          setShowPageStatus(false);
                        }}
                        onPressIn={() => setIsPressButton(true)}
                        onPressOut={() => setIsPressButton(false)}>
                        <View
                          style={[

                            styles.borderWidth,
                            {
                              borderRadius: styles.modalBtnCard.borderRadius,
                              // paddingHorizontal: nom.dp_px_20,
                              height: nom.dp_px_64,
                              width:nom.dp_px_87,
                              justifyContent: "center",
                              alignItems: 'center',
                              borderWidth:styles.borderWidth.borderWidth - nom.dp_px_1 / 2
                            },
                          ]}>
                          {isPressButton ? (<View style={{
                            position: 'absolute',
                            left: 0,
                            top: 0,
                            backgroundColor: 'black',
                            width: "100%",
                            height: nom.dp_px_10
                          }} />) : null}
                           
                          <Text style={{
                            fontSize: nom.dp_px_34,
                            marginTop: nom.dp_px_2,
                          }}>
                            {i18n.t('msg.go')}
                          </Text>
                        </View>
                      </TouchableWithoutFeedback>
                    </View>
                  </View>
                  <NumButtonContent
                    styles={styles}
                    handJumpNum={handJumpNum}
                    deleteJumpNum={deleteJumpNum}
                    pages={pages}
                    nom={nom}
                    screenHeight={screenHeight}
                    screenWidth={screenWidth}
                  />
                </View>
              </TouchableWithoutFeedback>
            </View>

          </TouchableWithoutFeedback>
        ) : null}

      </View>
    </Modal>
  );
};

const NumButtonContent = ({
  styles,
  handJumpNum,
  pages,
  nom,
  screenHeight,
  screenWidth,
  deleteJumpNum
}) => {
  const [isPressButton, setIsPressButton] = useState(false);

  return (<View
    style={[
      {
        width: screenWidth,
        height: nom.dp_px_199
      },
      styles.borderTopWidth,
      styles.flexCenter,
    ]}>
    {pages?.map((item, index) => {
      return (
        <NumButton
          styles={styles}
          handJumpNum={handJumpNum}
          item={item}
          nom={nom}
        />);
    })}
    <TouchableWithoutFeedback
      onPress={() => deleteJumpNum()}
      onPressIn={() => setIsPressButton(true)}
      onPressOut={() => setIsPressButton(false)}>
      <View
        style={[
          styles.borderWidth,
          {
            borderRadius: styles.modalBtnCard.borderRadius,
            width: nom.dp_px_102,
            height: nom.dp_px_102,
            justifyContent: 'center',
            alignItems: 'center',
            borderWidth:styles.borderWidth.borderWidth - nom.dp_px_1 / 2
          },
        ]}>
        {isPressButton ? (<View style={{
          position: 'absolute',
          left: 0,
          top: 0,
          backgroundColor: 'black',
          width: "100%",
          height: nom.dp_px_10
        }} />) : null}
          
        <Image
          style={{
            width: nom.dp_px_55,
            height: nom.dp_px_64,
            marginTop: nom.dp_px_2,
            resizeMode:'contain',
          }}
          source={require('../../assets/icon_delete.png')}
        />
      </View>
    </TouchableWithoutFeedback>
  </View>)
}

const NumButton = ({
  styles,
  handJumpNum,
  item,
  nom,
}) => {
  const [isPressButton, setIsPressButton] = useState(false);
  return (<TouchableWithoutFeedback
    onPress={() => handJumpNum(item)}
    onPressIn={() => setIsPressButton(true)}
    onPressOut={() => setIsPressButton(false)}>
    <View
      style={[
        styles.borderWidth,
        {
          marginRight: nom.dp_px_20,
          borderRadius: styles.modalBtnCard.borderRadius,
          width: nom.dp_px_102,
          height: nom.dp_px_102,
          justifyContent: 'center',
          alignItems: 'center',
          borderWidth:styles.borderWidth.borderWidth - nom.dp_px_1 / 2
        },
      ]}>
      {isPressButton ? (<View style={{
        position: 'absolute',
        left: 0,
        top: 0,
        backgroundColor: 'black',
        width: "100%",
        height: nom.dp_px_10
      }} />) : null}
      <Text style={[
        {
          fontSize: nom.dp_px_42,
          marginTop: nom.dp_px_2,
         

        }]}>{item}</Text>
    </View>
  </TouchableWithoutFeedback>);

}

export default ModalSelectSticker;
